package com.yueqian.bookshop.controller;

import com.mysql.jdbc.StringUtils;
import com.yueqian.bookshop.bean.RtnInfo;
import com.yueqian.bookshop.bean.Users;
import com.yueqian.bookshop.bean.UsersVo;
import com.yueqian.bookshop.mapper.UsersMapper;
import com.yueqian.bookshop.utils.CpachaUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UsersMapper usersMapper;
    /**
     * 生成验证码图片
     * 请求方式:GET
     * 请求url: /bookshop/user/verifyCode
     * 返回结果: JSON字符串
     *
     * @param tokenStr
     * @param request
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "verifyCode", method = RequestMethod.GET)
    public void verifyCode(String tokenStr, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        CpachaUtil cpachaUtil = new CpachaUtil(4, 100, 30);//指定验证码长度、图片宽度、高度
        //生成随机的验证码(四个字符的字符串)
        String generatorVCode = cpachaUtil.generatorVCode();
        //将验证码保存到session
        HttpSession session = request.getSession();
        //设置超时
        //session.setMaxInactiveInterval(60);//以秒为单位
        //将验证码存放到session，主要是在登录的servlet中实现跟前台的验证码进行匹配
        session.setAttribute("vCode", generatorVCode);
        System.out.println("-----------------保存session:" + session.getId() + " " + generatorVCode);
        //生成一个验证码图片，响应到前台
        BufferedImage g = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
        //回写
        ImageIO.write(g, "gif", resp.getOutputStream());
    }

    /**
     * 登录
     * 请求方式:POST
     * 请求url: /bookshop/user/login
     * 返回结果: JSON字符串
     *
     * @param request
     * @param users
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public RtnInfo login(HttpServletRequest request, UsersVo users) throws Exception {
        System.out.println("进入到了登录后台：\n"+users);
        // 创建一个RtnInfo对象，存放响应到前端的信息
        RtnInfo rtnInfo = new RtnInfo();
        // 对传过来的数据进行非空校验
        if(StringUtils.isNullOrEmpty(users.getPhone())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("手机号不能为空！");
        }else if(StringUtils.isNullOrEmpty(users.getPassword())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("密码不能为空！");
        }else if(StringUtils.isNullOrEmpty(users.getVcode())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("验证码不能为空！");
        }else{
            // 获取session中存储的验证码
            HttpSession session = request.getSession();
            String vcode = (String) session.getAttribute("vCode");
            // 校验验证码（判断前端传过来的验证码和服务器上的验证码是否一致）
            if(vcode==null || !vcode.equalsIgnoreCase(users.getVcode())){ // ABC = abc
                rtnInfo.setCode(-1);
                rtnInfo.setMsg("验证码输入错误！");
            }else{// 验证码通过，通过数据库校验phone，password是否正确
                Users query = usersMapper.login(users);
                if(query!=null){
                    request.getSession().setAttribute("user",query);
                    rtnInfo.setCode(1);
                    rtnInfo.setMsg("用户登录成功！");
                    rtnInfo.setResult(query);
                }else{
                    rtnInfo.setCode(0);
                    rtnInfo.setMsg("用户登录失败！");
                }
            }
        }
        return rtnInfo;// springboot会自动转成json字符串响应到前端
    }

    /**
     * 修改用户信息
     * 请求方式：POST
     * 请求URL：/bookshop/user/update
     * 请求参数：表单
     * 响应结果：JSON
     * @param users
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public RtnInfo update(Users users) throws IOException{
        RtnInfo rtnInfo = new RtnInfo();
        // 非空校验
        if(StringUtils.isNullOrEmpty(users.getNickname())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("姓名不能为空！");
        }
        if(StringUtils.isNullOrEmpty(users.getGender())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("性别不能为空！");
        }
        if(StringUtils.isNullOrEmpty(users.getAddress())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("住址不能为空！");
        }
        // 访问数据库
        if(usersMapper.updateUsers(users)>0){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("用户信息修改成功！");
        }else{
            rtnInfo.setCode(0);
            rtnInfo.setMsg("用户信息修改失败！");
        }
        return  rtnInfo;
    }

    /**
     * 用户密码修改
     * 请求的URL：/bookshop/user/updatePwd
     * 请求的方式：POST
     * 请求的类型：表单
     * 返回的类型：JSON
     * @param request
     * @param users
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "updatePwd",method = RequestMethod.POST)
    public RtnInfo updatePwd(HttpServletRequest request, UsersVo users) throws IOException{
        RtnInfo rtnInfo = new RtnInfo();
        // 从本地保存的session中获取用户编号
        Users u = (Users) request.getSession().getAttribute("user");
        if(u!=null){
            users.setUserId(u.getUserId());
        }
        // 校验旧密码是否存在
        users.setPassword(users.getOldPassword());// 旧密码
        if(usersMapper.checkOldPwd(users)>0){// 旧密码正确
            // 修改密码
            if(!StringUtils.isNullOrEmpty(users.getNewPassword())){// 非空校验
                users.setPassword(users.getNewPassword());// 新密码
                if(usersMapper.updatePwd(users)>0){
                    rtnInfo.setCode(1);
                    rtnInfo.setMsg("密码修改成功，请重新登录！");
                }else{
                    rtnInfo.setCode(0);
                    rtnInfo.setMsg("密码修改失败！");
                }
            }
        }else{
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("旧密码输入错误！");
        }
        return rtnInfo;
    }
}
